package com.edu.framework.websocket.service;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.edu.common.utils.DayNightUtil;
import com.edu.framework.websocket.message.weather.Coordinate;
import com.edu.framework.websocket.message.weather.WeatherVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.time.ZoneId;
import java.time.ZonedDateTime;

@Component
@Slf4j
public class WeatherService {

    private static final String auth_key = "Authorization";
    private static final String auth_value = "APPCODE 470acea5c1ff43728dfe096893090854";
    private static final String url_forecast6days = "https://mojibasic.market.alicloudapi.com/whapi/json/aliweather/briefforecast6days";
    private static final String url_aircondition = "https://mojibasic.market.alicloudapi.com/whapi/json/aliweather/aqi";

    private static final String json_path_aqi = "$.data.aqi.value";


    @Autowired
    private RestTemplate restTemplate;


    public String getWeather(Coordinate coordinate){
        String weather = getWeatherForecast6days(coordinate);
        String air = getAirCondition(coordinate);
        JSONObject today = JSONObject.parseObject(weather).getJSONObject("data").getJSONArray("forecast").getJSONObject(0);
        JSONObject airJson = JSONObject.parseObject(air);
        WeatherVO vo = new WeatherVO();
        StringBuffer temp = new StringBuffer();
        if(isDayTime(coordinate)){
            vo.setConditionId(today.getString("conditionIdDay"));
            temp.append(today.getString("conditionDay"));
        }else {
            vo.setConditionId(today.getString("conditionIdNight"));
            temp.append(today.getString("conditionNight"));
        }
        temp.append(" ");
        temp.append(today.getString("tempNight")).append("~").append(today.getString("tempDay")).append(" ℃");
        StringBuffer aqi = new StringBuffer();
        aqi.append("空气质量 ").append(JSONPath.eval(airJson,json_path_aqi));
        vo.setTemp(temp.toString());
        vo.setAqi(aqi.toString());

        return JSON.toJSONString(vo);
    }

    public String getAirCondition(Coordinate coordinate){
        return doPost(url_aircondition,coordinate);
    }

    public String getWeatherForecast6days(Coordinate coordinate){
        return doPost(url_forecast6days,coordinate);
    }


    public String doPost(String url,Coordinate coordinate){
        if(coordinate == null){
            throw new IllegalArgumentException("coordinate must not null");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add(auth_key,auth_value);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("lat", coordinate.getLat());
        body.add("lon", coordinate.getLon());

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
        String res = restTemplate.postForObject(url,httpEntity,String.class);
        if(log.isDebugEnabled()){
            log.debug(res);
        }
        return res;
    }


    private boolean isDayTime(Coordinate coordinate){
        double lat = Double.parseDouble(coordinate.getLat());
        double lon = Double.parseDouble(coordinate.getLon());
        //获取当前计算机默认的时区，也就是东八区时间
        ZoneId zoneId= ZoneId.systemDefault();
        ZonedDateTime now = ZonedDateTime.now(zoneId);
        return DayNightUtil.isDaytime(now,lat,lon);
    }

}
